<template>
  <div class="auth-container login-form">
    <h2 class="mb-4">🦊 {{ role === 'student' ? '学生登录' : '教师登录' }}</h2>
    <el-form :model="form" @submit.prevent="login">
      <el-form-item>
        <el-input 
          v-model="form.username" 
          placeholder="用户名" 
          prefix-icon="User" 
        />
      </el-form-item>
      <el-form-item>
        <el-input 
          v-model="form.password" 
          type="password" 
          placeholder="密码" 
          prefix-icon="Lock" 
          show-password 
        />
      </el-form-item>
      <el-button type="primary" native-type="submit" class="login-btn">
        登录
      </el-button>
    </el-form>
    <a class="back-link" @click="$router.push('/role-select')">
      <i class="bi bi-arrow-left"></i> 返回身份选择
    </a>
  </div>
</template>

<script>
import axios from 'axios';
import { updateUserState } from '../simpleStore.js';

import 'bootstrap-icons/font/bootstrap-icons.css';

export default {
  data() {
    return {
      selectedRole: '', // '' 或 'teacher'
      hoverRole: '',    // 鼠标悬停效果
      form: {
        username: '',
        password: ''
      }
    };
  },
  computed: {
    role() {
      return this.$route.query.role || 'student'
    }
  },
  mounted() {
    // 已登录则自动跳转
    const token = localStorage.getItem('token');
    const role = localStorage.getItem('role');
    if (token && role) {
      if (role === 'teacher') {
        this.$router.replace('/teacher/experiments');
      } else {
        this.$router.replace('/experiments');
      }
    }
  },
  methods: {
    async login() {
      try {
        const res = await axios.post('/api/login/', {
          ...this.form,
          role: this.role
        });
        const { token, role, username, user_id } = res.data;

        if (role !== this.role) {
        this.$message.error(`请从${role === 'teacher' ? '教师' : '学生'}入口登录！`);
        return;
      }
      
        localStorage.setItem('token', token);
        localStorage.setItem('role', role);
        localStorage.setItem('username', username);
        localStorage.setItem('user_id', user_id);
        axios.defaults.headers.common['Authorization'] = `Token ${token}`;
        updateUserState();
        if (role === 'teacher') {
          this.$router.push('/teacher/experiments');
        } else {
          this.$router.push('/experiments');
        }
      } catch (error) {
        let errorMessage = '登录失败，请检查用户名或密码';
        if (error.response) {
          // 后端返回了具体的错误信息
          console.error('Backend error:', error.response.data);
           if (error.response.data && error.response.data.detail) {
            // 处理后端自定义身份入口错误
            errorMessage = error.response.data.detail;
          } else if (error.response.data && error.response.data.non_field_errors) {
            errorMessage = error.response.data.non_field_errors.join(', ');
          } else if (typeof error.response.data === 'string') {
            errorMessage = error.response.data;
          } else if (error.response.status === 404) {
            errorMessage = '登录接口未找到，请检查前端请求路径和代理配置。';
          }
        } else if (error.request) {
          // 请求已发出，但没有收到响应
          console.error('No response:', error.request);
          errorMessage = '无法连接到服务器，请检查网络或后端服务是否运行。';
        } else {
          errorMessage = error.message;
        }
        this.$message.error(errorMessage);
        console.error(error);
      }
    }
  }
};
</script>

<style scoped>
.auth-container {
  max-width: 400px;
  margin: 10vh auto;
  padding: 40px 30px 30px 30px;
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.15);
  text-align: center;
  transition: box-shadow 0.3s;
}

.el-form {
  margin-bottom: 10px;
}

.el-input {
  font-size: 1.05rem;
}

.login-btn {
  width: 100%;
  font-size: 1.08rem;
  padding: 12px 0;
  border-radius: 8px;
  margin-top: 8px;
  background: linear-gradient(90deg, #409eff 0%, #66b1ff 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(64,158,255,0.08);
  transition: background 0.3s;
}

.login-btn:hover {
  background: linear-gradient(90deg, #66b1ff 0%, #409eff 100%);
}

.back-link {
  display: inline-block;
  margin-top: 18px;
  color: #409eff;
  font-size: 0.98rem;
  cursor: pointer;
  text-decoration: none;
  transition: color 0.2s;
}
.back-link:hover {
  color: #1d78c1;
  text-decoration: underline;
}
</style>